define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    "index_url": "general/Operate/get_template",
                    "add_url": "general/Operate/add_template",
                    "edit_url": "general/Operate/edit_template",
                    "switch_url": "general/Operate/switch_template",
                    "del_url": "general/Operate/del_template",
                    "multi_url": "",
                }
            });

            $('.add_banner').on('click', function(){
                let sort = $('#banner').find('.ml').length;
                let html = `<div class="form-group" sort="${sort + 1}">
                                <label for="c-banner${sort}" class="control-label">${__('Carousel img')}${sort + 1}:</label>
                                <input name="banner[${sort}][id]" type="hidden" value="">
                                <div class="input-group">
                                    <input id="c-banner${sort}" class="form-control" size="50" name="banner[${sort}][url]" type="text" value="">
                                    <div class="input-group-addon no-border no-padding">
                                        <span>
                                            <button type="button" id="faupload-banner${sort}" class="btn btn-danger faupload" data-input-id="c-banner${sort}" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp" data-multiple="false" data-preview-id="p-banner${sort}"><i class="fa fa-upload"></i> ${__('Upload')}</button>
                                        </span>
                                        <span>
                                            <button type="button" id="fachoose-banner${sort}" class="btn btn-primary fachoose" data-input-id="c-banner${sort}" data-mimetype="image/*" data-multiple="false"><i class="fa fa-list"></i> ${__('Choose')}</button>
                                        </span>
                                    </div>
                                    <span class="msg-box n-right" for="c-banner${sort}"></span>
                                </div>
                                <ul class="row list-inline faupload-preview" id="p-banner${sort}"></ul>

                                <div class="pd-10">${__('Tips')}</div>
                                <div class="form-group">
                                    <label class="control-label">${__('Url')}</label>
                                    <input class="form-control" name="banner[${sort}][item_url]" type="text" value="" placeholder="${__('bannerUrl')}">
                                </div>
                                <div class="form-group">
                                    <label class="control-label">${__('Sort')}</label>
                                    <input class="form-control" name="banner[${sort}][sort]" type="text" value="0" placeholder="${__('bannerSort')}">
                                </div>
                            </div>
                            <div class="ml"></div>`;
                $('#banner').children('.form-group:last-child').before(html);
                Form.events.plupload("#banner");
            })

            var table = $("#template");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                search: false,
                commonSearch: false,
                showExport: false,
                showToggle: false,
                showColumns: false,
                columns: [
                    [
                        {field: 'code', title: __('TemplateCode')},
                        {field: 'type', title: __('TemplateType'), formatter: Controller.api.formatter.type},
                        {field: 'state', title: __('TemplateState')},
                        {field: 'content', title: __('TemplateContent')},
                        {field: 'item', title: __('TemplateItem'), formatter: Controller.api.formatter.item},
                        {field: 'send_type', title: __('TemplateSendType'), formatter: Controller.api.formatter.send_type},
                        {field: 'url', title: __('TemplateURL')},
                        {field: 'status', title: __('Status'), formatter: Controller.api.formatter.status, events: Controller.api.events.status},
                        {field: 'createtime', title: __('Createtime'), formatter: Table.api.formatter.datetime, sortable: true},
                        {field: 'operate', title: __('Operate'), formatter: Controller.api.formatter.operate, events: Controller.api.events.operate}
                    ]
                ],
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            Form.api.bindevent($("form[role=form]"),function(data,ret){
                window.location.reload();
            });
        },
    
        api:{
            formatter:{
                type:function(value,row,index){
                    return value?__('Validate'):__('Notice');
                },
                item:function(value,row,index){
                    return value?__('Single Item'):__('All Item');
                },
                send_type:function(value,row,index){
                    return value?__('Automatic'):__('Manual');
                },
                status:function(value,row,index){
                    let label = '';
                    if(value){
                        label = `<span class="btn btn-warning btn-xs status">${__('Disable')}</span>`;
                    } else {
                        label = `<span class="btn btn-success btn-xs status">${__('Normal')}</span>`;
                    }
                    return label;
                },
                operate:function(value,row,index){
                    let div =   `<div class="operate">
                                    <span class="btn btn-primary btn-xs edit">${__('Edit')}</span>
                                    <span class="btn btn-danger btn-xs del">${__('Del')}</span>
                                </div>`;
                    return div;
                }
            },
            events:{
                status:{
                    'click .status':(e, value, row, index)=>{
                        e.stopPropagation();
                        let title = value?'启用':'禁用';
                        let l = Layer.confirm(`确定${title}该模板?`,['是','否'],function(){
                            Fast.api.ajax({
                                url: $.fn.bootstrapTable.defaults.extend.switch_url,
                                data: {
                                    id: row.id,
                                    value: value?0:1
                                }
                            },function (data,ret) {
                                Layer.close(l);
                                setTimeout(()=>{
                                    $("a.btn-refresh").trigger("click");
                                },500);
                            },(data,ret)=>{
                                Layer.close(l);
                            })
                        })
                    }
                },
                operate:{
                    'click .edit':(e, value, row, index)=>{
                        e.stopPropagation();
                        let url = $.fn.bootstrapTable.defaults.extend.edit_url+`?id=${row.id}`;
                        Fast.api.open(url,'编辑',{'area': ['300px', '50%']});
                    },
                    'click .del':(e, value, row, index)=>{
                        e.stopPropagation();
                        let l = Layer.confirm(`确定删除该模板?`,['是','否'],function(){
                            Fast.api.ajax({
                                url: $.fn.bootstrapTable.defaults.extend.del_url,
                                data:{
                                    id:row.id
                                }
                            },function (data,ret) {
                                Layer.close(l);
                                setTimeout(()=>{
                                    $("a.btn-refresh").trigger("click");
                                },500);
                            },(data,ret)=>{
                                Layer.close(l);
                            })
                        })
                    },
                }
            }
        }
    }

    return Controller;
});
